package zju.zhu.model;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class JdbcResourceQuery implements ResourceQuery {

	private JdbcTemplate jdbc;

	public JdbcResourceQuery(DataSource dataSource) {
		this.jdbc = new JdbcTemplate(dataSource);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Resource> getResourceByUserId(String userId) {
		try{
			return this.jdbc.<Resource>query("select userId, token from resource where userId = ?", resourceRowMapper, userId);
		} catch(EmptyResultDataAccessException e){
			return null;
		}
	}

	@SuppressWarnings("rawtypes")
	private static final RowMapper resourceRowMapper = new RowMapper() {
		public Object mapRow(ResultSet rslt, int rowNum) throws SQLException {
			return new Resource(rslt.getString("userId"), rslt.getString("token"));
		}
	};

}
